package com.pp.small.common.base;

import com.pp.small.common.enums.ResponseEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 统一的返回数据
 *
 * @author FrozenWatermelon
 * @date 2020/7/3
 */
@Slf4j
@Data
public class BaseResult<T> implements Serializable {

	/**
	 * 状态码
	 */
	private String code;

	/**
	 * 信息
	 */
	private String msg;

	/**
	 * 数据
	 */
	private T data;

	public static <T> BaseResult<T> success(T data) {
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setData(data);
		baseResult.setCode(ResponseEnum.OK.value());
		baseResult.setMsg(ResponseEnum.OK.getMsg());
		return baseResult;
	}

	public static <T> BaseResult<T> success() {
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setCode(ResponseEnum.OK.value());
		baseResult.setMsg(ResponseEnum.OK.getMsg());
		return baseResult;
	}

	/**
	 * 前端显示失败消息
	 * @param msg 失败消息
	 * @return
	 */
	public static <T> BaseResult<T> showFailMsg(String msg) {
		log.error(msg);
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setMsg(msg);
		baseResult.setCode(ResponseEnum.SHOW_FAIL.value());
		return baseResult;
	}

	public static <T> BaseResult<T> fail(String code, String msg) {
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setCode(code);
		baseResult.setMsg(msg);
		baseResult.setData(null);
		return baseResult;
	}

	public static <T> BaseResult<T> fail(ResponseEnum responseEnum) {
		log.error(responseEnum.toString());
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setMsg(responseEnum.getMsg());
		baseResult.setCode(responseEnum.value());
		return baseResult;
	}

	public static <T> BaseResult<T> fail(ResponseEnum responseEnum, T data) {
		log.error(responseEnum.toString());
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setMsg(responseEnum.getMsg());
		baseResult.setCode(responseEnum.value());
		baseResult.setData(data);
		return baseResult;
	}

	public static <T> BaseResult<T> transform(BaseResult<?> oldBaseResult) {
		BaseResult<T> baseResult = new BaseResult<>();
		baseResult.setMsg(oldBaseResult.getMsg());
		baseResult.setCode(oldBaseResult.getCode());
		log.error(baseResult.toString());
		return baseResult;
	}

	public boolean isSuccess() {
		return Objects.equals(ResponseEnum.OK.value(), this.code);
	}
}
